/*

Edited by David Schlesinger


*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <math.h>
#include <pthread.h>
#include <stdint.h>
#include "types.h"
#include <time.h>
#include <sys/timeb.h>
#include "delay.h"

#include "waypoints.h"
//#define NEED_MODENAMES
#include "platform_modes.h"
//#undef NEED_MODENAMES
#include "platform_types.h"
#include "status.h"
#include "command.h"
#include "platformstatus.h"

#ifdef DEBUG
#include "logfile.h"
#endif

#include "cssl.h"

#include <pthread.h>

typedef struct{
	double tempC;
	double speCond;
	double o2Sat;
	double o2Chrg;
	double pH;
}SONDE_STATUS;

static SONDE_STATUS ss;
static cssl_t *serial;

/***********************************************
	seeks for '#' signal to pass NMEA string
***********************************************/
int wait_sonde(char *buf)
{

	char *pS;
	int rval;
	char *temp;

        temp = strchr(buf, '$');
        if(temp != NULL) {
                return 1;
        }

	pS = strrchr(buf, '#');
	
	/* no # signal yet seen */
	if(pS == NULL){
		return 0;
	}
	rval = sscanf(pS, "#");
	if(rval == EOF){
		printf("parse # incomplete\n");
		return 0;
	}

	/* we found #, lets output that we found it */
	//printf("\n\n*************************************\n");
	//printf("SONDE: # FOUND,  Begin Data Collection\n");
	//printf("*************************************\n\n");
	
	return 1;
}

int sonde_GetStart(void)
{

	UBYTE buf[1];
	int length;
	
	length = cssl_getdata(serial,buf, sizeof(buf));

	//printf("%s",(char *)buf);


	/*send NMEA signal THE "\r" is important!!!!r*/ 
	if(wait_sonde((char *)buf)){
		cssl_putstring(serial, "NMEA\r");
		//printf("NMEA Signal Sent\n\n");
		return 1;
	}

	return 0;
}

/************************************************
*parse_sonde()
*
*parse sonde output buffer into SONDE_STATUS
*********************************************/
static void parse_sonde(char *buf){

        char *pS;
        int rval;

        /*set pS to point to the first point where $ occurs */
        pS = strrchr(buf, '$');

        if(pS == NULL){
                printf("parse_sonde(): No '$' found  - No Data Was Parsed\n");
                return;
        }

        // Note - seems to change?
        rval = sscanf(pS,
"$YSI,1,%lf,6,%lf,6,0,14,%lf,96,%lf,18,%lf*",&(ss.tempC),&(ss.speCond),&(ss.o2Sat),&(ss.o2Chrg),&(ss.pH));
        
        if(rval == EOF){
                printf("parse_sonde(): Incomplete string\n");
                return;
        }
        
        return;
}

/**********************************************
* sonde_GetData()
*
* Fetch data fromthe cssl library and parse it
**********************************************/
static void sonde_GetData(void)
{


        /*
                Note:
                        So it seems that we read 8 bits at a time no matter what baud/bit rate is.
                        Thus we just loop to fix this issue, though a more premenant solution should
                        be found. Also, malloc!
        */

        /* Set it to an Arbitrary Buffer Size */
	
	while(1){
	
        char*  buf = malloc(2000);
        char* temp = malloc(100);

        int length;


        int i = 0;
        
        for( i = 0; i < 8; i++) {
                length = cssl_getdata(serial, temp, 8);
                strcat(buf,temp);
        }
        

        parse_sonde(buf);
        temp = "\n";
	
	}

        return;
}

/*********************************************
* sondeInit()
*
*Initialize the cssl library
*********************************************/
static int sondeInit( char *port, int baud, int bits, int stopbits)
{

	ss.tempC = 0.0;
	ss.speCond = 0.0;
	ss.o2Sat = 0.0;
	ss.o2Chrg = 0.0;
	ss.pH = 0.0;
	
	cssl_start();
	
	serial = cssl_open(port, NULL, 0, baud, bits, 0, 1);
	if(!serial){
		printf("%c\n" , *cssl_geterrormsg());
		return(-1);
	}
	
	cssl_settimeout(serial, 1);
	
	return(0);
	
}

/*******************************************************
* sonde_Start()
*
* Called from the main program to set up the sonde port
********************************************************/
int sonde_Start(char *port)
{
	pthread_t thread1;
	int rval, rval1;
	
	int baud = 9600;

	int bits = 8;
	int stopbits = 1;
	int sondeStart = 0;
	/*need to add parity = none*/
	
	rval = sondeInit(port,baud,bits,stopbits);
	//printf("%d\n", rval);
	while(sondeStart == 0){
		sondeStart = sonde_GetStart();
	}

	rval1 = pthread_create( &thread1, NULL, sonde_GetData, (void*) NULL);

	return(rval);
}

/******************************************************
* sonde_GetStatus()
*
* Returns the current sonde status from the local data struct
******************************************************/
void sonde_GetStatus(STATUS *s) 
{
	STATUS s1;
	
	s1 = platformstatus_GetStatus();
	
	s->tempC.position.dLatDeg = s1.dLatDeg;
	s->tempC.position.dLonDeg = s1.dLonDeg;
	s->speCond.position.dLatDeg = s1.dLatDeg;
	s->speCond.position.dLonDeg = s1.dLonDeg;
	s->o2Sat.position.dLatDeg = s1.dLatDeg;
	s->o2Sat.position.dLonDeg = s1.dLonDeg;
	s->o2Chrg.position.dLatDeg = s1.dLatDeg;
	s->o2Chrg.position.dLonDeg = s1.dLonDeg;
	s->pH.position.dLatDeg = s1.dLatDeg;
	s->pH.position.dLonDeg = s1.dLonDeg;
	
	strcpy(s->tempC.sTime,s1.sTime);
	strcpy(s->speCond.sTime,s1.sTime);
	strcpy(s->o2Sat.sTime,s1.sTime);
	strcpy(s->o2Chrg.sTime,s1.sTime);
	strcpy(s->pH.sTime,s1.sTime);
	
	s->tempC.nTime = s1.nTime;
	s->speCond.nTime = s1.nTime;
	s->o2Sat.nTime = s1.nTime;
	s->o2Chrg.nTime = s1.nTime;
	s->pH.nTime = s1.nTime;	
		

	//printf("Main.c Loop Running - Get Data From Sonde\n");
	//sonde_GetData();
	s->tempC.dValue = ss.tempC;
	s->speCond.dValue = ss.speCond;
	s->o2Sat.dValue = ss.o2Sat;
	s->o2Chrg.dValue = ss.o2Chrg;
	s->pH.dValue = ss.pH;

        FILE *f;
        f = fopen("sonde_data.txt","a");

	fprintf(f,"%lf, %lf, %s, %lf, %lf, %lf, %lf, %lf\n", s1.dLatDeg, s1.dLonDeg, s1.sTime, ss.tempC, ss.speCond, ss.o2Sat, ss.o2Chrg, ss.pH);	
	fclose(f);

	printf("Parsed data output: %lf, %lf, %lf, %lf, %lf\n\n", s->tempC.dValue, s->speCond.dValue, s->o2Sat.dValue, s->o2Chrg.dValue, s->pH.dValue);	


	return;
}

